<?php
$loader->requireOnce('includes/inPatientCore/TreatingPatientProcessor.class.php');
$loader->requireOnce('includes/inPatientCore/InPatientCoreErrorCode.class.php');
$loader->requireOnce('includes/inPatientCore/InPatientCoreException.class.php');
$loader->requireOnce('includes/inPatientCore/TestDiagnosisTicketManagement.class.php');
$loader->requireOnce('includes/Icd10Selector/Icd10Selector.class.php');
$loader->requireOnce('controllers/C_Patient.class.php');
/**
 * Processor for emergency dept.
 * @package module.dept_emer.includes
 * @author hdviet
 * @version $Id$
 * @copyright 2009 LHV Company
 */
class EmerProcessor extends TreatingPatientProcessor {
	/**
	 * constructor
	 */
	private $testTicketManagerment;
	function __construct($controller) {
		parent::__construct($controller);
		$this->testTicketManagerment = new  TestDiagnosisTicketManagement();
	}


	/**
	 *
	 * @param $ticketId
	 * @param $treatmentResult
	 * <br>
	 * EnumerationConstant::IN_PATIENT_TREATMENT_RESULT_RECOVER;
	 * <br>
	 * EnumerationConstant::IN_PATIENT_TREATMENT_RESULT_NCHANGE
	 * <br>
	 * EnumerationConstant::IN_PATIENT_TREATMENT_RESULT_SERIOUS
	 * <br>
	 * EnumerationConstant::IN_PATIENT_TREATMENT_RESULT_FATAL     *
	 * @return nothing.
	 * @throw InpatientCoreException  if fail
	 * <br>
	 * error code:
	 * <br>
	 * InPatientCoreErrorCode::COMMON_ERROR
	 *
	 */
	public function emerRecordEmrInfoCOLeave($ticketId, $enumTreatmentResult) {
		$inPatientEmrObj = Celini::newORDO("InPatientEmr");
		$em = EnumManager::getInstance();
		$treatmentResult = $em->lookupKey(EnumerationConstant::IN_PATIENT_TREATMENT_RESULT,
		$enumTreatmentResult);
		if ($treatmentResult == false) {
			throw new InpatientCoreException("Not support enum [ EnumerationConstant::IN_PATIENT_TREATMENT_RESULT,$treatmentResult ]",
			InPatientCoreErrorCode::COMMON_ERROR);
		}
		$data = array('enum_treatment_result'=>$treatmentResult,'ticket_id'=>$ticketId);

		//save emr data for this patient.
		$inPatientEmrObj->recordEmrInfo($data);

	}

	/**
	 *
	 * @param $ticketId
	 * @param $treatmentResult
	 * <br>
	 * EnumerationConstant::IN_PATIENT_TREATMENT_RESULT_RECOVER;
	 * <br>
	 * EnumerationConstant::IN_PATIENT_TREATMENT_RESULT_NCHANGE
	 * <br>
	 * EnumerationConstant::IN_PATIENT_TREATMENT_RESULT_SERIOUS
	 * <br>
	 * EnumerationConstant::IN_PATIENT_TREATMENT_RESULT_FATAL     *
	 * @return nothing.
	 * @throw InpatientCoreException  if fail
	 * <br>
	 * error code:
	 * <br>
	 * InPatientCoreErrorCode::COMMON_ERROR
	 *
	 */
	public function emerRecordEmrInfoCOChangeDept($ticketId, $enumTreatmentResult) {
		$this->emerRecordEmrInfoCOLeave($ticketId, $enumTreatmentResult);
	}

	public function loadIPPatientInfo($ticketId) {
		$inPatientTicketMg = Celini::newORDO("InPatientTicket");
		$ticketObj = $inPatientTicketMg->getTicketInfo($ticketId);
		$person = Celini::newORDO("Person", $ticketObj['patient_id']);
		$patient = Celini::newORDO("Patient", $ticketObj['patient_id']);
		$vitalSignObj = Celini::newORDO("VitalSign");
		$vitalSign = $vitalSignObj->getLastestVitalSign($ticketObj['patient_id']);
		VitalSign::normalizeData4Display($vitalSign);
		$generalDiagnosisObj = Celini::newORDO("GeneralDiagnosis");
		$generalDiagnosis = $generalDiagnosisObj->getGeneralDiagnosis($ticketId);
		GeneralDiagnosis::normalizeData4Display($generalDiagnosis);
		
		$inPatientEmrObj = Celini::newORDO("InPatientEmr");
        $inPatientEmr = $inPatientEmrObj->getEmrInfo($ticketId);
		

		$path = $this->controller->view->path;
		$this->controller->view->path = "patient_instant_info";

		if ($generalDiagnosis != null) {
			$this->controller->assign('lastestUpdate','');
			$this->controller->assign('allergyDetail',$generalDiagnosis['general_allergy_detail']);
			$this->controller->assign('drugAllergy', $generalDiagnosis['drug_allergy_detail']);
		}
		$this->controller->assign('inPatientEmr',$inPatientEmr);
		$this->controller->assign('pName',$person->get_name());
		$this->controller->assign('pAddress',$person->getAddress());
		$this->controller->assign('pPhone',$person->getPhoneNumber());
		$this->controller->assign('pAge', $person->getAge());
		$this->controller->assign('pCareer', $person->getCareerName());
		$this->controller->assign('pGender', $person->getGender());
		$this->controller->assign('rName',$patient->getRelativeName());
		$this->controller->assign('rAddress',$patient->getRelativeAddress());
		$this->controller->assign('rPhone',$patient->getRelativeNumber());
		if ($vitalSign != null) {
			$this->controller->assign('lastestVitalSignDate',$vitalSign['examine_time']);
			$this->controller->assign('pulse',$vitalSign['pulse']);
			$this->controller->assign('temperature',$vitalSign['temperature']);
			$this->controller->assign('bp',$vitalSign['blood_presure_s'] . "/" . $vitalSign['blood_presure_d']);
			$this->controller->assign('sp02',$vitalSign['sp02']);
			$this->controller->assign('respiratoryRate',$vitalSign['respiratory_rate']);
		}

		$form = $this->controller->view->render('patient_info.html');
		$this->controller->view->path = $path;
		return $form;
	}
	/**
	 * Save dianogsis data
	 * @param $generalDiagnosis
	 * @param $emr
	 * @return saved general diagnosis id.
	 */
	public function saveGeneralDiagnosis($generalDiagnosis = array()) {
		
		$generalDiagnosisObj = Celini::newORDO("GeneralDiagnosis");
		try{
        	$generalDiagnosisId = $generalDiagnosisObj->saveGeneralDiagnosis($generalDiagnosis);
		}
		catch(InpatientCoreException $ex){
			echo($ex->getMessage());
		}
        return $generalDiagnosisId;	
		
	}
	public function getIcd10Id($icd10Code) {
		$icd10Id =   ORDataObject::factory('Icd10')->getObjectbyCode($icd10Code)->getId();
		if($icd10Code != '' && $icd10Id == ''){
			throw new InpatientCoreException('Wrong ICD10 code', InPatientCoreErrorCode::WRONG_ICD10_CODE);
		}
		return $icd10Id;
	}
	
	/**
	 * Validate user-key-in ICD10 code, only use in tab 'General Diagnosis', page 'Instant Info'
	 * @param $icd10Code
	 * @return validate result: array('errorCode' => ['OK'|'ERROR'], 'errorMess' => sth)
	 */
	public function validateKeyInIcd10($icd10Code){
		$icd10Id =   ORDataObject::factory('Icd10')->getObjectbyCode($icd10Code)->getId();
		$result			=	array('errorCode' => 'OK', 'mess' => '');
		if($icd10Code != '' && $icd10Id == ''){
			$result['errorCode'] = InPatientCoreErrorCode::WRONG_ICD10_CODE;
			$result['mess'] = InPatientCoreErrorCode::getErrorMess(InPatientCoreErrorCode::WRONG_ICD10_CODE);
		}
		else if($icd10Code != '' && $icd10Id != ''){
			$result['mess']= Celini::newORDO('Icd10', $icd10Id)->getLocalizedText('name');
		}
		return $result;
	}
	/**
	 * Save emr data.
	 * @param $emerEmr
	 * @return saved emer emr record id.
	 */
    public function saveEmerEmr($emerEmr = array()) {
        
        $inpatientEmr = Celini::newORDO("InPatientEmr");
        $inpatientEmrId = $inpatientEmr->recordEmrInfo($emerEmr);
        return $inpatientEmrId;        
    }
	
	
	

	/**
	 * Load general diagnosis panel of give ticketId
	 * @param $ticketId
	 * @return html object
	 */
	public function loadIPGeneralDiagnosis($ticketId) {
		$inPatientTicketMg = Celini::newORDO("InPatientTicket");
		$ticketObj = $inPatientTicketMg->getTicketInfo($ticketId);
		$listOfVitalSign = $this->listVitalSign($ticketObj['patient_id']);
		$generalDiagnosisObj = Celini::newORDO("GeneralDiagnosis");
		$generalDiagnosis = $generalDiagnosisObj->getGeneralDiagnosis($ticketId);
		GeneralDiagnosis::normalizeData4Display($generalDiagnosis);

		$inPatientEmrObj = Celini::newORDO("InPatientEmr");
		$inPatientEmr = $inPatientEmrObj->getEmrInfo($ticketId);

		$employeeObj = Celini::newORDO("Employee");
		$doctorList = $employeeObj->getEmployeeOfDepartment($this->controller->_me->get_department_id(),EmployeeType::DOCTOR_ID, true);

		$path = $this->controller->view->path;
		$this->controller->view->path = "patient_instant_info";

		
		$glasgowEList = Utils::getEnumArrayKey(EnumerationConstant::IN_PATIENT_GLASGOW_E);
		$glasgowVList = Utils::getEnumArrayKey(EnumerationConstant::IN_PATIENT_GLASGOW_V);
		$glasgowMList = Utils::getEnumArrayKey(EnumerationConstant::IN_PATIENT_GLASGOW_M);
		
		// adjust glasgow list lable
		foreach($glasgowEList as $key => $name){
			$name = "($key) " . $name;
			$glasgowEList[$key] = $name;
		}
		foreach($glasgowVList as $key => $name){
			$name = "($key) " . $name;
			$glasgowVList[$key] = $name;
		}
		foreach($glasgowMList as $key => $name){
			$name = "($key) " . $name;
			$glasgowMList[$key] = $name;
		}
		
		$this->controller->assign('ticketId', $ticketId);
		$this->controller->assign('patientId', $ticketObj['patient_id']);

		$this->controller->assign('generalDiagnosis',$generalDiagnosis);
		$this->controller->assign('listOfVitalSign',$listOfVitalSign);
		$this->controller->assign('inPatientEmr',$inPatientEmr);
		$this->controller->assign('doctorList',$doctorList);
		$this->controller->assign('glasgowEList',$glasgowEList);
		$this->controller->assign('glasgowVList',$glasgowVList);
		$this->controller->assign('glasgowMList',$glasgowMList);

		$glasgowEVM = $generalDiagnosis['enum_glasgow_e'] + $generalDiagnosis['enum_glasgow_v'] + $generalDiagnosis['enum_glasgow_m'];
		$this->controller->assign('glasgowEVM', $glasgowEVM);
		$orders =   L10nHelper::getYMDorder();
		$this->controller->assign('datePart_0', $orders[0]);
		$this->controller->assign('datePart_1', $orders[1]);
		$this->controller->assign('datePart_2', $orders[2]);
		$form = $this->controller->view->render('general_diagnosis.html');
		$this->controller->view->path = $path;
		return $form;
	}
	/**
	 * Create new empty vital sign.
	 * @param $patientId
	 * @return vitalSignId.
	 */
	public function addVitalSign($patientId, $examineTime) {
		
		$vitalSignObj = Celini::newORDO("VitalSign");        
		$vitalSignId = $vitalSignObj->addNewVitalSign($patientId, $examineTime);
		return $vitalSignId;
		
	}
	
    /**
     * list vital sign.
     * @param $patientId
     * @return vitalSignId.
     */
    public function listVitalSign($patientId) {
        
       $vitalSignObj = Celini::newORDO("VitalSign");
       $listOfVitalSign = $vitalSignObj->listOfVitalSign($patientId);
        foreach ($listOfVitalSign as &$vitalSign) {
        	VitalSign::normalizeData4Display($vitalSign);        	
        }
        
        return $listOfVitalSign;
        
    }
	
    /**
     * Create new empty vital sign.
     * @param $patientId
     * @return vitalSignId.
     */
    public function saveVitalSign($vitalSignId, $data = array()) {
        
        $vitalSignObj = Celini::newORDO("VitalSign");        
        $vitalSignId = $vitalSignObj->saveVitalSign($vitalSignId, $data);
    }
	
/**
     * del vital sign.
     * @param $patientId
     * @return nothing.
     */
    public function delVitalSign($vitalSignId) {
        
        $vitalSignObj = Celini::newORDO("VitalSign");        
        $vitalSignObj->delVitalSign($vitalSignId);
    }
    /**
     * Load test assign of instant panel.
     * @param $ticketId
     * @return unknown_type
     */
    public function loadLabAssignmentPanel($ticketId, $listOfLabAssignment) {
    	$path = $this->controller->view->path;
        $this->controller->view->path = "patient_instant_info";
        
        $this->controller->assign('ticketId', $ticketId);
        
        $this->controller->assign('listOfLabAssignment', $listOfLabAssignment);        
        $form = $this->controller->view->render('test_assign.html');
        $this->controller->view->path = $path;
        return $form;
    	
    }
    
/**
     * Load test assign of instant panel.
     * @param $ticketId
     * @return unknown_type
     */
    public function loadTestResultFormInput($ticketId) {
        $path = $this->controller->view->path;
        $this->controller->view->path = "emer_test_input_result";
        $listOfAssignedTest = $this->testTicketManagerment->listOfTestTicket($ticketId);
        foreach ($listOfAssignedTest as &$testTicket) {
            TestDiagnosisTicketManagement::normalizeData4Display($testTicket);
            
        }
        $this->controller->assign('ticketId', $ticketId);
        
        $this->controller->assign('listOfAssignedTest', $listOfAssignedTest);        
        $form = $this->controller->view->render('test_input_result.html');
        $this->controller->view->path = $path;
        return $form;
        
    }
    
    public function buildAssignedTestItemResultInput($ticketId, $testDiagnosisTicketId) {
    	$listAssignedTestItem = $this->testTicketManagerment->listOfAssignedTestItem($testDiagnosisTicketId);
        $assignedTestArr = $this->testTicketManagerment->buildTestArray4Print($listAssignedTestItem);
        $path = $this->controller->view->path;
        $this->controller->view->path = "emer_test_input_result";
        $this->controller->assign('assignedTestArr', $assignedTestArr );
        $this->controller->assign('ticketId', $ticketId);
        $form = $this->controller->view->render('test_item_input.html');
        $this->controller->view->path = $path;
        return $form;
    }
    
    
    /**
     * Load test assign of instant panel.
     * @param $ticketId
     * @return unknown_type
     */
    public function buildIPTestAssignDesktop($ticketId) {
    	
    	$employeeObj = Celini::newORDO("Employee");
        $doctorList = $employeeObj->getEmployeeOfDepartment($this->controller->_me->get_department_id(),EmployeeType::DOCTOR_ID, true);        
        $path = $this->controller->view->path;
        $this->controller->view->path = "patient_instant_info";
        $orders =   L10nHelper::getYMDorder();
         $this->controller->assign('ticketId', $ticketId);
        $this->controller->assign('datePart_0', $orders[0]);
        $this->controller->assign('datePart_1', $orders[1]);
        $this->controller->assign('datePart_2', $orders[2]);
        $this->controller->assign('doctorList',$doctorList);
        $testTree = $this->testTicketManagerment->buildTestGroupTreeHtml4Desktop($ticketId);        
        $this->controller->assign('htmlListGroupOfTest',$testTree->getHtmlList());  
        $this->controller->assign('assignedTestItem',''); 
        $form = $this->controller->view->render('test_assign_desktop.html');
        $this->controller->view->path = $path;
        return $form;
        
    }
     /* @param $testTicketInfo
     * array(ticket_id,requested_time,diagnosis,ticket_id,doctor_id, is_done)
     * @param $assignedTest
     * array([test_service_id],...)
     * @return id of added test ticket.
     */

    public function addAssignedTest($testTicketInfo, $assignedTest) {
    	return $this->testTicketManagerment->addAssignedTest($testTicketInfo, $assignedTest);
    	
    }
    
    public function getListOfTestByGroup($testGroupId) {
    	return $this->testTicketManagerment->getListOfTestByGroup($testGroupId);
    }
    
    
    
 /**
     * Load test assign of instant panel.
     * @param $ticketId
     * @return unknown_type
     */
    public function buildIPTestAssignDesktop4Edit($ticketId, $testDiagnosisTicketId) {
        $employeeObj = Celini::newORDO("Employee");
        $doctorList = $employeeObj->getEmployeeOfDepartment($this->controller->_me->get_department_id(),EmployeeType::DOCTOR_ID, true);        
        $path = $this->controller->view->path;
        $this->controller->view->path = "patient_instant_info";
        $orders =   L10nHelper::getYMDorder();
         $this->controller->assign('ticketId', $ticketId);
        $this->controller->assign('datePart_0', $orders[0]);
        $this->controller->assign('datePart_1', $orders[1]);
        $this->controller->assign('datePart_2', $orders[2]);
        $this->controller->assign('doctorList',$doctorList);
        $testTree = $this->testTicketManagerment->buildTestGroupTreeHtml4Desktop($ticketId);        
        $this->controller->assign('htmlListGroupOfTest',$testTree->getHtmlList());
        $assignedTestTicket = $this->testTicketManagerment->getAssignedTestTicket($testDiagnosisTicketId);
        
        TestDiagnosisTicketManagement::normalizeData4Display($assignedTestTicket);
        $requestTimePart =  L10nHelper::getDateParts($assignedTestTicket['requested_time']);
        
        $this->controller->assign('assignedTestTicket', $assignedTestTicket);
        $this->controller->assign('requestTimePart', $requestTimePart);
        $listAssignedTestItem = $this->testTicketManagerment->listOfAssignedTestItem($testDiagnosisTicketId);
       
        
       
        $this->controller->assign('listAssignedTestItem', $listAssignedTestItem );
        $form = $this->controller->view->render('test_assign_desktop_edit.html');
        $this->controller->view->path = $path;
        return $form;
        
    }
    
    public function printAssignTestTicket($ticketId, $testDiagnosisTicketId) {
    	$inPatientTicketMg = Celini::newORDO("InPatientTicket");
        $ticketObj = $inPatientTicketMg->getTicketInfo($ticketId);
        
        $employeeObj = Celini::newORDO("Employee");
        $person = Celini::newORDO("Person", $ticketObj['patient_id']);
        $patientCode = Celini::newOrdo("Patient", $ticketObj['patient_id'])->getPatientCode();
        
        $path = $this->controller->view->path;
        $this->controller->view->path = "patient_instant_info";
        $orders =   L10nHelper::getYMDorder();
         $this->controller->assign('ticketId', '');
        $this->controller->assign('datePart_0', $orders[0]);
        $this->controller->assign('datePart_1', $orders[1]);
        $this->controller->assign('datePart_2', $orders[2]);
        $this->controller->assign('person',$person);
        $this->controller->assign('departmentName',$this->controller->_me->get_department_name());
        $this->controller->assign('patientCode',$patientCode);
        
        
        $assignedTestTicket = $this->testTicketManagerment->getAssignedTestTicket($testDiagnosisTicketId);
        TestDiagnosisTicketManagement::normalizeData4Display($assignedTestTicket);
        $this->controller->assign('assignedTestTicket', $assignedTestTicket);
        $listAssignedTestItem = $this->testTicketManagerment->listOfAssignedTestItem($testDiagnosisTicketId);
        $assignedTestArr = $this->testTicketManagerment->buildTestArray4Print($listAssignedTestItem);
        $this->controller->assign('assignedTestArr', $assignedTestArr );
        $form = $this->controller->view->render('test_assign_desktop_print.html');
        $this->controller->view->path = $path;
        return $form;        
    }
    /**
     * Build html form for check out.
     * @param $ticketId
     * @return string html form
     */
    public public function buildCheckOutDeathHtmlForm($ticketId, $departmentId) {
        $path = $this->controller->view->path;
        $this->controller->view->path = "emer_reception";
        $inPatientTicketMg = Celini::newORDO("InPatientTicket");
        $ticketObj = $inPatientTicketMg->getTicketInfo($ticketId);
        $patientId = $ticketObj['patient_id'];
        
        
        // Person object
        $objPatient     =   Celini::newORDO('Person', $patientId);
        // Localized birthday
        $birthDay       =   $objPatient->getLocalizedDate('date_of_birth');
        // EmerReception object
        $objReception   =   ORDataObject::factory('EmerReception')->getLatestObjectByPatientId($patientId);
        // Check-in datetime
        $checkInDate =   L10nHelper::getDateParts($objReception->getCheckInDate());
        $checkInTime =   $objReception->getCheckInTime();
        // Career list
        $trlPatient =   new C_Patient();
        $careerList =   $trlPatient->getCareerList();
        // Patient info
        $patientObj		=	Celini::newORDO('Patient', $patientId);
        $patientCode	=	$patientObj->getPatientCode();
        $departmentId	=	Celini::newORDO('Ticket', $ticketId)->getDepartmentId();
        $department		=	Celini::newORDO('Department', $departmentId)->getLocalizedText('name');
        $doctorList =   ORDataObject::factory('Employee')->getEmployeeOfDepartment($departmentId,
            EmployeeType::DOCTOR_ID, true);
        $orders     =   L10nHelper::getYMDorder();
        $provinceList =     ORDataObject::factory('Province')->getProvinceList();
        $districtList =     ORDataObject::factory('District')->getDistrictList($objPatient->getProvinceId());
        
        $this->controller->assign('datePart_0', $orders[0]);
        $this->controller->assign('datePart_1', $orders[1]);
        $this->controller->assign('datePart_2', $orders[2]);
        $this->controller->assign('careerList', $careerList);
        $this->controller->assign('patientId', $patientId);
        $this->controller->assign('doctorList', $doctorList);
        $this->controller->assign('birthDays', L10nHelper::getDateParts($birthDay));
        $this->controller->assign('checkInDate', $checkInDate);
        $this->controller->assign('checkInTime', $checkInTime);
        $this->controller->assign('provinceList', $provinceList);
        $this->controller->assign('districtList', $districtList);
        $this->controller->assign_by_ref('patient', $objPatient);
        $this->controller->assign_by_ref('departmentId', $departmentId);
        $this->controller->assign_by_ref('department', $department);
        $this->controller->assign_by_ref('patientCode', $patientCode);
        $form = $this->controller->view->render('report_dead_inside.html');
        $this->controller->view->path = $path;
        return $form;
    }
    
    /**
     * Check out leave.
     * @param $ticketId
     * @throw InpatientCoreException if checking out fail
     */
    public public function checkOutDeath($ticketId, $constTreatmentType,$dateTime, $data = array()) {
    	
    	parent::checkOutDeath($ticketId, $constTreatmentType,$dateTime);
    }
    
    public function saveAllergyInfo($ticketId, $allergy, $generalAllergy, $drugAllergy){
    	$generalDiagnosisObj = Celini::newORDO("GeneralDiagnosis");
		try{
        	$generalDiagnosisId = $generalDiagnosisObj->saveAllergyInfo($ticketId, $allergy, $generalAllergy, $drugAllergy);
		}
		catch(InpatientCoreException $ex){
			echo($ex->getMessage());
		}
        return $generalDiagnosisId;
    }

}
?>